package com.wang.common.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.wang.common.util.FileUtil;
import com.wang.common.util.PoiUtil;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.util.DateFormatUtil;
import com.wang.common.util.EncryptUtil;
import com.wang.common.util.PageInfoUtil;
import com.wang.common.util.RegexUtil;

/**
 * 存储的是所有Servlet层的公共代码 ~工具类 ~所有公共的代码也放过来
 *
 * @author wangshMac
 */
public class BaseServlet extends HttpServlet {
    /**
     * jsp文件路径
     */
    protected String path;
    protected String updateFlag;
    /**
     * 加密算法工具类
     */
    protected EncryptUtil encryptUtil = new EncryptUtil();
    /**
     * 引入工具类
     */
    protected DateFormatUtil dateFormatUtil = new DateFormatUtil();
    protected RegexUtil regexUtil = new RegexUtil();
    protected FileUtil fileUtil = new FileUtil();
    protected PoiUtil poiUtil = new PoiUtil();

    /**
     * 公共的一些操作
     *
     * @param request 请求对象
     */
    protected void commonOper(HttpServletRequest request) {
        /* 存储一些公共的变量 */
        request.setAttribute("websiteUrl", ConstatFinalUtil.CONFIG_JSON.get("website.url"));
        request.setAttribute("websiteFileUrl", ConstatFinalUtil.CONFIG_JSON.get("website.fileUrl"));
        request.setAttribute("websiteHeadUrl", ConstatFinalUtil.CONFIG_JSON.get("website.head.url"));
        /* 存储系统配置表中的所有变量 */
        request.setAttribute("sys_pro_map", ConstatFinalUtil.SYS_PRO_MAP);
        /* 从数据库中读取一些变量 */
        request.setAttribute("sys_map", ConstatFinalUtil.SYS_PRO_MAP);
    }

    /**
     * 生成一个查询列表公共的搜索条件
     *
     * @param request 请求对象
     * @return 搜索条件的集合
     */
    protected Map<String, Object> proccedSearch(HttpServletRequest request) {
        Map<String, Object> condMap = new HashMap<String, Object>();
        String keyword = request.getParameter("keyword");

        String status = request.getParameter("status");
        String st = request.getParameter("st");
        String ed = request.getParameter("ed");
        /* 将查询条件存储到request中 */
        request.setAttribute("keyword", keyword);
        request.setAttribute("status", status);
        request.setAttribute("st", st);
        request.setAttribute("ed", ed);
        /* 关键字 */
        if (keyword == null) {
            keyword = "";
        }

        /* 状态 */
        if (status == null) {
            status = "";
        }

        /* 查询的起始时间和结束时间 */
        Date stDate = null;
        Date edDate = null;
        if (st != null && !"".equalsIgnoreCase(st) && ed != null && !"".equalsIgnoreCase(ed)) {
            stDate = this.dateFormatUtil.strDateTime(st);
            edDate = this.dateFormatUtil.strDateTime(ed);
        }
        condMap.put("keyword", keyword);
        condMap.put("status", status);
        condMap.put("stDate", stDate);
        condMap.put("edDate", edDate);
        return condMap;
    }

    /**
     * 生成分页对象
     *
     * @param request 请求对象
     * @return 分页对象
     */
    protected PageInfoUtil proccedPageInfo(HttpServletRequest request) {
        String currentPage = request.getParameter("currentPage");
        String pageSize = request.getParameter("pageSize");
        /* 分页 */
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        try {
            /* 将字符串转换成整数,有风险,
             * 字符串为a,转换不成不整数
             *  */
            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
        } catch (NumberFormatException e) {
        }
        return pageInfoUtil;
    }

    /**
     * 从session中获取用户或者管理员信息
     *
     * @param request 请求对象
     * @param type    类型(users,admins)
     * @return 对象
     */
    protected Object findObjfromSession(HttpServletRequest request, String type) {
        HttpSession session = request.getSession();
        if ("users".equalsIgnoreCase(type)) {
            return session.getAttribute("users");
        } else if ("admins".equalsIgnoreCase(type)) {
            return session.getAttribute("admins");
        }
        return null;
    }

    /**
     * 返回json字符串
     *
     * @param returnStr 响应字符串
     * @param response  响应对象
     */
    public void printOut(String returnStr, HttpServletResponse response) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(returnStr);
            out.flush();
            out.close();
        } catch (IOException e) {
            ConstatFinalUtil.SYS_LOGGER.error("为客户端返回信息出错了;", e);
        }
    }

    /**
     * 文件上传工具类
     *
     * @param request 请求对象
     * @return 存储上传对象集合
     */
    protected Map<String, Object> fileUploadUtil(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        /* 所有的Request请求只要是二进制流的方式提交,必须用common-fileupload来解析 */
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        try {
            Collection<Part> parts = request.getParts();
            for (Part part : parts) {
                /* 不是表单字段;二进制字段
                 * jpg
                 * */
                String fileName = part.getName();
                InputStream is = part.getInputStream();
                /* 如何处理二进制图片呢?
                 * 放到Service来做
                 *  */
                resultMap.put("fileName", fileName);
                resultMap.put("is", is);
            }

            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry<String, String[]> me : parameterMap.entrySet()) {
                String key = me.getKey();
                String[] valArr = me.getValue();
                String val = null;
                if (valArr != null) {
                    val = valArr[0];
                }
            }
        } catch (Exception e) {
        }
        return resultMap;
    }
}
